package com.carl.leetcode.pointer;

/**
 * Created by carlXie on 2016/3/21.
 */
public class RemoveElement {
    public static void main(String[] args) {
        int[] nums = {3, 2, 2, 3};
        int newLen = removeElement(nums, 3);
        System.out.println("len: " + newLen);

        for (int i = 0; i < newLen; i++) {
            System.out.print(nums[i] + " ");
        }

    }

    public static int removeElement(int[] nums, int val) {
        if(nums == null || nums.length == 0) return 0;

        int frontIndex = 0;
        int rearIndex = nums.length - 1;

        while(frontIndex < rearIndex) {
            if(nums[frontIndex] == val) {
                while(frontIndex < rearIndex && nums[rearIndex] == val)
                    -- rearIndex;
                if(frontIndex == rearIndex) return frontIndex;
                nums[frontIndex++] = nums[rearIndex];
                nums[rearIndex--] = val;
            } else {
                ++ frontIndex;
            }
        }


        return nums[frontIndex] == val? frontIndex : frontIndex + 1;
    }
}
